import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Space,
  TypographyText
} from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { cinemaApi } from '@/apis'
import jdCouponApi from '@/apis/jdCouponApi'
import { JdCouponItem } from '@/apis/jdCouponTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, formatDate, optionsToMap } from '@/utils'
import { sceneTypeOptions } from '@/views/order/constants'

import ImportPhoneList from './importPhoneList'
import SendRecordList from './sendRecordList'

export default defineComponent({
  name: 'JindouCoupon',
  setup() {
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)
    const showRecordDlg = ref(false)
    const showSendDlg = ref(false)
    const sendLoading = ref(false)
    const curOptionItem = ref({} as JdCouponItem)
    const snedItem = ref({} as any)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '抵扣券名称',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '可用场景',
              field: 'type',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: sceneTypeOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            title: 'ID',
            field: 'id'
          },
          {
            title: '抵扣券名称',
            field: 'name',
            minWidth: 200
          },
          {
            title: '可用场景',
            field: 'type',
            minWidth: 150,
            formatter: ({ cellValue }) => {
              return optionsToMap(sceneTypeOptions)[cellValue]
            }
          },
          {
            title: '卡片有效期',
            minWidth: 310,
            slots: {
              default: 'timeRangeRow'
            }
          },
          {
            title: '状态',
            field: 'status',
            fixed: 'right',
            width: 100,
            slots: {
              default: 'status'
            }
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 300
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await jdCouponApi.getJdCouponList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()

    function handleCreate() {
      router.push({
        name: 'JdCouponCreateLimit'
      })
    }

    function handleEdit(row) {
      router.push({
        name: 'JdCouponCreateLimit',
        query: {
          id: row.id
        }
      })
    }

    function handleDisable(data) {
      showConfirm({
        content: data.status == 1 ? '确认禁用该优惠卷？' : '确认启用该优惠卷？',
        onOk: async () => {
          try {
            await jdCouponApi.setupJdCoupon(data.id, data.status == 1 ? 0 : 1)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    //发放记录
    function handleRecord(row) {
      showRecordDlg.value = true
      curOptionItem.value = row
    }

    //发放优惠券
    function handleSend(row) {
      snedItem.value = {}
      snedItem.value.couponId = row.id
      snedItem.value.sign = '1'
      showSendDlg.value = true
    }

    //确定发放优惠券
    async function sendConfirm() {
      try {
        sendLoading.value = true
        await jdCouponApi.sendCoupon(snedItem.value)
        message.success('优惠券发放成功')
        showSendDlg.value = false
      } finally {
        sendLoading.value = false
      }
    }

    onMounted(() => {
      bus.on('refreshTimeLimitList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    return {
      tableRef,
      tableConfig,
      showRecordDlg,
      curOptionItem,
      showSendDlg,
      snedItem,
      sendLoading,
      handleSend,
      handleCreate,
      handleEdit,
      handleDisable,
      handleRecord,
      sendConfirm
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            timeRangeRow: ({ row }) => (
              <Space>
                <span>
                  {row.startTime
                    ? `${formatDate(row.startTime)} 至 ${formatDate(
                        row.endTime
                      )}`
                    : '无'}
                </span>
              </Space>
            ),
            status: ({ row }) => {
              return (
                <Space>
                  {row.status == 0 ? (
                    <TypographyText type="danger">禁用</TypographyText>
                  ) : (
                    <TypographyText type="success">启用</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDisable(row)}
                >
                  {row.status == 1 ? '禁用' : '启用'}
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleRecord(row)}
                >
                  发放记录
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleSend(row)}
                >
                  发放优惠券
                </Button>
              </Space>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button type="primary" onClick={this.handleCreate}>
                    新增
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showRecordDlg}
          title="发放记录"
          destroyOnClose
          width={900}
          footer={null}
        >
          <SendRecordList id={this.curOptionItem.id} />
        </Modal>
        <Modal
          v-model:visible={this.showSendDlg}
          confirmLoading={this.sendLoading}
          title="发放优惠券"
          destroyOnClose
          onOk={this.sendConfirm}
          width={500}
        >
          <Form labelCol={{ span: 5 }}>
            <FormItem label={'发放张数'} required>
              <InputNumber
                v-model:value={this.snedItem.num}
                placeholder="请输入"
                maxlength={10}
                min={0}
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label={'发放原因'} required>
              <Input
                maxlength={60}
                v-model:value={this.snedItem.reason}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label={'发放人员'} required>
              <ImportPhoneList
                v-model:phones={this.snedItem.mobileList}
              ></ImportPhoneList>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
